package com.gzu.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gzu.shop.annotation.Access;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.common.ResultStatus;
import com.gzu.shop.constant.JwtClaimsConstant;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.constant.RoleConst;
import com.gzu.shop.constant.StatusConstant;
import com.gzu.shop.entity.User;
import com.gzu.shop.enumeration.AccessLevel;
import com.gzu.shop.exception.AccountExistedException;
import com.gzu.shop.mapper.UserMapper;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.properties.JwtProperties;
import com.gzu.shop.service.UserService;
import com.gzu.shop.util.JwtUtil;
import com.gzu.shop.util.PasswordBcryptUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @author Clown
 */
@RestController
@RequestMapping("/admin")
@Access(AccessLevel.ADMIN)
@AllArgsConstructor
@Slf4j
@Tag(name = "用户管理相关接口")
public class UserController extends BaseController<UserService, User> {
    private JwtProperties jwtProperties;
    private UserMapper userMapper;

    // 加上管理员权限注解
    @Operation(summary = "管理员注册")
    @GetMapping("/register")
    public Result<Void> userRegister(@RequestBody User user) {

        // 查询用户是否已经存在
        boolean exists = userMapper.exists(new QueryWrapper<User>()
                .eq("username", user.getUsername()));
        // 用户存在，则抛出异常
        if (exists) {
            throw new AccountExistedException(MessageConstant.ACCOUNT_EXISTS);
        }
        // 得到原始密码
        String plainPassword = user.getPassword();
        // 得到加密后密码
        String hashedPassword = PasswordBcryptUtil.encryptPassword(plainPassword);
        // 将加密后密码存入
        user.setPassword(hashedPassword);
        // 设置角色
        user.setRole(RoleConst.USER);
        // 设置状态
        user.setStatus(StatusConstant.OPEN);
        // 插入数据
        userMapper.insert(user);

        return Result.success(ResultStatus.SUCCESS);
    }


    @Override
    public Result<Void> addEntity(User user) {
//        log.info("add:{}", user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 查询用户是否已经存在
        boolean exists = userMapper.exists(queryWrapper.eq("username", user.getUsername()));
        // 用户存在，则抛出异常
        if (exists) {
            throw new AccountExistedException(MessageConstant.ACCOUNT_EXISTS);
        }

        return super.addEntity(user);
    }

    @Override
    public Result<User> getById(Integer id) {
        return super.getById(id);
    }

    @Override
    public Result<Void> deleteById(Long id) {
        return super.deleteById(id);
    }

    @Override
    public Result<Void> deleteBatch(List<Long> ids) {
        return super.deleteBatch(ids);
    }

    @Override
    public Result<List<User>> selectBatch(List<Long> ids) {
        return super.selectBatch(ids);
    }

    @Override
    public Result<Void> editById(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 查询用户是否已经存在
        boolean exists = userMapper.exists(queryWrapper.eq("username", user.getUsername()));
        // 用户存在，则抛出异常
        if (exists) {
            throw new AccountExistedException(MessageConstant.ACCOUNT_EXISTS);
        }
        return super.editById(user);
    }

    @Override
    public Result<IPage<User>> page(int startPage, int pageSize, SearchCondition<User> searchCondition) {
        return super.page(startPage, pageSize, searchCondition);
    }

    @Override
    public Result<List<User>> searchAll(SearchCondition<User> searchCondition) {
        return super.searchAll(searchCondition);
    }

    @Operation(description = "得到用户Token,并将userID,role存入token中")
    private String getToken(User user) {
        HashMap<String, Object> claims = new HashMap<>();
        // 将userID,role存入Map中
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        claims.put(JwtClaimsConstant.ROLE, user.getRole());
        // 得到token
        return JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
    }




}
